package jersey;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataMultiPart;

import dto.ResponseDto;
import util.FileUtils;
import util.PropertiesUtils;

@Path("/")
public class ImageUpload {
	
	private final static Logger logger = LogManager.getLogger(ImageUpload.class);
	
	private String path;
	
	public ImageUpload() {
		path = PropertiesUtils.getProperties("image.path");
	}
	
	@Path("/image/upload")
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public ResponseDto upload(FormDataMultiPart form) {
		ResponseDto resultDto = new ResponseDto();
		resultDto.setCode(-1);
		FormDataBodyPart  imgPart = form.getField("img");
		FormDataBodyPart key = form.getField("key");
		InputStream inputStream = null;
		OutputStream outputStream = null;
		if (imgPart==null) {
			resultDto.setMessage("must have img");
			return resultDto;
		}
		try {
			inputStream = imgPart.getValueAs(InputStream.class);
//			if (inputStream.available()==0) {
//				resultDto.setMessge("img not available");
//				return resultDto;
//			}
			if (key==null) {
				resultDto.setMessage("must have key");
			}
			String imageName = key.getValue();
			FileUtils.save(path+imageName, inputStream, outputStream);
			resultDto.setCode(1);
			resultDto.setMessage("success");
			return resultDto;
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}finally {
			try {
				if (inputStream!=null) {
					inputStream.close();
				}
				if (outputStream!=null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e);
			}
		}
		resultDto.setMessage("error happen");
		return resultDto;
	}
	
	
	@Path("/test")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public ResponseDto test() {
		ResponseDto resultDto = new ResponseDto(1,"success",null);
		return resultDto;
	}

}
